package thread;

import java.util.concurrent.CountDownLatch;

import static java.lang.Thread.sleep;

/**
 * Created by fanzhenyu02 on 2020/6/23.
 */
public class CountDownLatchExample {


    class Service {
        private CountDownLatch latch;

        public Service(CountDownLatch latch) {
            this.latch = latch;
        }

        public void exec() {
            try {
                System.out.println(Thread.currentThread().getName() + " execute task. ");
                Thread.sleep(100);
                System.out.println(Thread.currentThread().getName() + " finished task. ");
            } catch (Exception e) {

            } finally {
                latch.countDown();
            }
        }

    }

    public void run() throws Exception {
        CountDownLatch latch = new CountDownLatch(5);
        Service service = new Service(latch);
        Runnable task = () -> service.exec();

        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(task);
            thread.start();
        }

        System.out.println("main thread await. ");
        latch.await();
        System.out.println("main thread finishes await. ");
    }


    public static void main(String[] args) throws Exception {
        CountDownLatchExample example = new CountDownLatchExample();
        example.run();
    }
}


